<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/4/24/024
 * Time: 20:37
 */

namespace app\admin\model;

use think\Model;
use think\facade\Session;
use app\common\model\Currency;
use app\api\model\Token;
use app\api\model\MemberProfile;
use app\api\model\MemberInfo;


class Member extends Model
{
    const Member_TYPE = [
        1 => '单文本',
        2 => '多文本',
        3 => '富文本',
    ];

    /**
     * 获取单条
     * @param $id
     * @return array|null|\PDOStatement|string|\think\Model
     */
    public function _findOne($id){
        $arr = [
            'mi.apprentice_num',
            'mi.apprentice_return_commission_balance_today',
            'mi.apprentice_return_commission_balance',
            'mi.login_num',
            'mi.login_num_today',
            'mi.login_continuity_num',
            'mi.sign_num',
            'mi.sign_continuity_num',
            'mi.sign_continuity_seven_num',
            'mi.finish_task_num',
            'mi.finish_task_balance',
            'mi.withdraw_balance',
            'mi.exchange_balance',
            'mi.exchange_gold',
            'mi.onday_turntable_num',
            'mi.total_balance',
            'mi.total_gold',
        ];
        $str = implode(',',$arr);
        $data = $this->alias('m')
            ->field('m.*, p.user_name as paname, ml.title as level_name, t.token, mp.image, mp.nick_name, mp.sex, mp.pid as pdd, mp.cid, mp.address,mp.birthday, mp.birthdayint ,mp.real_name,'.$str)
            ->join('token t', 'm.id=t.mid', 'LEFT')
            ->join('member_level ml', 'm.level_id=ml.id', 'LEFT')
            ->join('member_profile mp', 'm.id=mp.mid', 'LEFT')
            ->join('member_info mi', 'm.id=mi.mid', 'LEFT')
            ->join('member p', 'm.pid = p.id', 'LEFT')
            ->where([['m.id', '=', $id]])
            ->find();
        return $data;
    }

    
    /**
    * 通过名称获取信息
    */
    public function _findByName($name){
        return $this->where([['title', '=', $name]])->find();
    }
    
    //校验用户名是否存在
    public function _checkName($value){
        $data = $this->where([['title', '=', $value]])->find();
        if(!empty($data)){
            $this->error = '已存在';
            return false;
        }
        return true;
    }
    

    /**
    * 校验是否被冻结
    */
    public function _checkStatus($id){
        $data = $this->where(array('id'=>$id, 'status'=>1))->find();
        if(empty($data)){
            $this->error = '已禁用';
            return false;
        }
        return true;
    }

    /**
     * 列表
     * @param array $condition
     * @param int $page_size
     * @param string $order_by
     * @return \think\Paginator
     */
    public function _list($condition = [], $page_size = PAGE_SIZE_ADMIN, $order_by = 'm.created desc'){
        $arr = [
            'mi.apprentice_num',
            'mi.apprentice_return_commission_balance_today',
            'mi.apprentice_return_commission_balance',
            'mi.login_num',
            'mi.login_num_today',
            'mi.login_continuity_num',
            'mi.sign_num',
            'mi.sign_continuity_num',
            'mi.sign_continuity_seven_num',
            'mi.finish_task_num',
            'mi.finish_task_balance',
            'mi.withdraw_balance',
            'mi.exchange_balance',
            'mi.onday_turntable_num',
            'mi.total_balance',
            'mi.total_gold',
        ];
        //var_dump($condition);die;
        $str = implode(',',$arr);
        $obj = $this->alias('m')
            ->field('m.*, ml.title as level_name, t.token, mp.image, mp.nick_name, mp.sex, mp.pid as pdd, mp.cid, mp.address,mp.birthday, mp.birthdayint,'.$str)
            ->join('token t', 'm.id=t.mid', 'LEFT')
            ->join('member_level ml', 'm.level_id=ml.id', 'LEFT')
            ->join('member_profile mp', 'm.id=mp.mid', 'LEFT')
            ->join('member_info mi', 'm.id=mi.mid', 'LEFT')
            ->order($order_by);
        if(empty($condition)){
            $condition = "m.is_del = -1";
        }else{
            $condition .= " and m.is_del = -1 ";
        }
            //->select();
        //dump($obj);die;
        $result = get_page($obj, $condition, $page_size);
       
        return $result;
    }

    /**
     * 添加
     * @param $post
     * @return bool
     */
    public function _create($post, $config){
        $tel = trim($post['tel']);
        $member = $this->where([['user_name', '=', $tel]])->find();
        if(!empty($member)){
            $this->error = '手机号已存在';
            return false;
        }
        $tel = $post['tel'];
        
       
        $pwd = $post['pwd'];
        if(!preg_match("/^(13|14|15|16|17|18|19)[0-9]{9}$/", $tel)){
            $this->error = "请输入合法的手机号";
            return false;
        }
        if(!preg_match("/^[0-9a-zA-Z]{6,16}$/", $pwd)){
            $this->error = "请输入6至16位的密码";
            return false;
        }
        $pwd = createPassword($post['pwd']);
        //直接注册步骤：1.写入会员，2创建token，3创建会员资料，4创建会员平台统计信息，
        $unique = strtoupper(nocstr(10));
        $this->unique($unique);
        $invitation_code = strtoupper(nocstr(10));
        $this->invitation_code($invitation_code);
        
        $currencyModel = new Currency;
        $qrcode = $currencyModel->_qrcode($unique,$invitation_code);
        $data = [
            'unique' => $unique,
            'user_name' => $tel,
            'pwd' => $pwd,
            'invitation_code' => $invitation_code,
            'qrcode' => $qrcode,
            'updated' => time(),
            'created' => time(),
        ];
        
        //var_dump($data);die;
        $this->startTrans();
        $ret = $this->save($data);
        if(!$ret){
            $this->error = '登录失败';
            $this->rollback();
            return false;
        }
        
        $mid = $this->getLastInsID();
        //var_dump($mid);
        $token_ob = new Token;
        $ret1 = $token_ob->_createToken($mid);
        //var_dump($ret1);die;
        if(!$ret1){
            $this->error = $token_ob->getError();
            $this->rollback();
            return false;
        }
        
        $profile_model = new MemberProfile;
        $nickname = $post['nickname'];
        $ret2 = $profile_model->_addProfile($mid, $config['DEFAULT_HEAD'],$nickname);
        if(!$ret2){
            $this->error = $profile_model->getError();
            $this->rollback();
            return false;
        }
        
        //4.创建会员平台统计信息
        $info_model = new MemberInfo;
        $ret3 = $info_model->_addInfo($mid);
        if(!$ret3){
            $this->error = $info_model->getError();
            $this->rollback();
            return false;
        }
        
        $this->commit();
        

        return true;
    }
    
    /**
    *   生成唯一平台标识
    *   @param unique string 平台唯一ID
    *   @return string
    */
    public function unique($unique){
        $user = $this->where(array('unique'=>$unique))->find();
        if(!empty($user)){
            $unique = strtoupper(nocstr(10));
            $this->unique($unique);
        }else{
            return $unique;
        }
    }
    
    /**
    *   生成邀请码
    *   @param unique string 平台唯一ID
    *   @return string
    */
    public function invitation_code($invitation_code){
        $user = $this->where(array('invitation_code'=>$invitation_code))->find();
        if(!empty($user)){
            $invitation_code = strtoupper(nocstr(10));
            $this->invitation_code($invitation_code);
        }else{
            return $invitation_code;
        }
    }


    /**
     * 删除
     * @param $id
     * @return bool
     */
    public function _remove($id){
        $result = $this->_findOne($id);
        if(!$result){
            $this->error = '无此';
            return false;
        }
    
        $result->is_del = 1;
        if(!$result->save()){
            $this->error = '操作失败';
            return false;
        }
        
        return true;
    }
    /**
     * 批量删除
     * @param $id
     * @return bool
     */
    public function _removeAll($id){
        $ret = $this->where([['id', 'in', $id]])->update(['is_del'=>1]);
        if(!$ret){
            $this->error = '操作失败';
            return false;
        }
        
        return true;
    }


    /**
     * 详情
     * @param $id
     * @return array|bool
     */
    public function _detail($id){
        $result = $this->_findOne($id)->toArray();
        if(!$result){
            $this->error = '无此数据';
            return false;
        }
        return $result;
    }


    /**
     * 修改
     * @param $post
     * @return bool
     */
    public function _modify($post){
        $result = $this->_findOne($post['id']);
        if(empty($result)){
            $this->error = '不存在';
            return false;
        }
        $data = $this->where([['title', '=', trim($post['name'])]])->find();
        //var_dump($data);die;
        if(!empty($data)){
            if($data->id != $result->id){
                $this->error = '已存在';
                return false;
            }
        }
        
        if(isset($post['type'])) $result->type = (int)$post['type'];
        if(isset($post['title'])) $result->title = trim($post['name']);
        if(isset($post['content'])) $result->content = $post['content'];
        $result->updated = time();
        if($result->save() === false){
            $this->error = '操作失败';
            return false;
        }
        
        
        return true;
    }

    /**
    * 设置状态
    */
    public function _setStatus($request){
        $ff = $request['ff'];
        $id = $request['id'];
        if($ff == 1){
            $success = "冻结成功";
            $error = "冻结失败";
        }elseif($ff == -1){
            $success = "启用成功";
            $error = "启用失败";
        }
        
        
        $where = array('id'=>$id,'status'=>$ff);

        $data = $this->where($where)->find();
        if(empty($data)){
            $this->error = '该数据状态已改变';
            
            return false;
        }
        $data->status = -$ff;
        $ret = $data->save();
        if(!$ret){
            $this->error = $error;
            return false;
        }
        
        
        return true;
    }
    

    /**
    * 数据总条数
    */
    public function _count($where = []){
        return $this->alias('m')->where($where)->count();
    }

    /**
    * 获取条件
    */
    public function _where($request){
        $p = isset($request['page']) ? $request['page'] : 1;
        $start = isset($request['start']) ? $request['start'] : '';
        $end = isset($request['end']) ? $request['end'] : '';
        $type = isset($request['type']) ? $request['type'] : '';
        $user_name = isset($request['user_name']) ? $request['user_name'] : '';
        
        $request['page'] = $p;
        $request['start'] = $start;
        $request['end'] = $end;
        $request['user_name'] = $user_name;
        $request['type'] = $type;
        
        $search = $request;
        
        $user_name = htmlspecialchars(addslashes(str_replace(' ', '', $user_name)));
        $request['user_name'] = str_replace('%', "\%", $user_name);
        
        $tmp = $request;
        foreach($tmp as $k=>$v){
            if(empty($v)){
                unset($tmp[$k]);
            }
        }
        $where = '';
        foreach($tmp as $k=>$v){
            if($k == 'start'){
                $start = strtotime($v);
                $where .= "m.created >= $start and ";
            }elseif($k == 'end'){
                $end = strtotime($v) + 24*3600;
                $where .= "m.created <= $end and ";
            }elseif($k == 'user_name'){
                $where .= "m.user_name like '%$v%' and ";
            }elseif($k == 'type'){
                $where .= "m.type = $v and ";
            }
        }
        if(!empty($where)){
            $where = substr($where, 0, -4);
        }
        return array('search'=>$search,'where'=>$where);
    }
}